/**
 * @Project : ProgrammingExercises
 * @Package : Leetcode
 * @File : Q0015.java
 * @Author : WangRuoyu
 * @Date 2022/11/18 17:53
 */

package leetcode;

import java.util.*;


public class Q0015 {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            if (nums[i] + nums[i + 1] + nums[i + 2] > 0 || nums[i] + nums[nums.length - 2] + nums[nums.length - 1] < 0)
                continue;
            int l = i + 1;
            int r = nums.length - 1;
            while (l < r) {
                if (nums[i] + nums[l] + nums[r] == 0) {
                    ArrayList<Integer> tmp = new ArrayList<>();
                    tmp.add(nums[i]);
                    tmp.add(nums[l]);
                    tmp.add(nums[r]);
                    res.add(tmp);
                    l++;
                    while (l < r && nums[l] == nums[l - 1]) l++;
                    r--;
                    while (l < r && nums[r] == nums[r + 1]) r--;
                } else if (nums[i] + nums[l] + nums[r] > 0) {
                    r--;
                } else {
                    l++;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Q0015 sl = new Q0015();
        int[] nums = {-1, -1, -1, -1, 0, 1};
        System.out.println(sl.threeSum(nums));
    }
}
